const express = require('express');
const { authenticateMiniappToken } = require('../middleware/auth');
const UserAddress = require('../models/UserAddress');

const router = express.Router();

// 所有地址路由都需要认证
router.use(authenticateMiniappToken);

/**
 * 获取当前用户的地址列表
 * GET /api/addresses
 */
router.get('/', async (req, res) => {
  try {
    const userId = req.user.userId;
    const addresses = await UserAddress.getByUserId(userId);
    res.success(addresses, '获取地址列表成功');
  } catch (error) {
    console.error('获取地址列表失败:', error);
    res.error('获取地址列表失败', 500, error.message);
  }
});

/**
 * 获取地址详情
 * GET /api/addresses/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    
    const address = await UserAddress.findById(id, userId);
    if (!address) {
      return res.error('地址不存在', 404);
    }

    res.success(address, '获取地址详情成功');
  } catch (error) {
    console.error('获取地址详情失败:', error);
    res.error('获取地址详情失败', 500, error.message);
  }
});

/**
 * 创建新地址
 * POST /api/addresses
 */
router.post('/', async (req, res) => {
  try {
    const userId = req.user.userId;
    const {
      recipient_name, phone_number, province, city, district,
      detailed_address, is_default = false
    } = req.body;

    // 验证必填字段
    if (!recipient_name || !phone_number || !province || !city || !district || !detailed_address) {
      return res.error('请填写完整的地址信息', 400);
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone_number)) {
      return res.error('请输入正确的手机号', 400);
    }

    const addressData = {
      user_id: userId,
      recipient_name: recipient_name.trim(),
      phone_number: phone_number.trim(),
      province: province.trim(),
      city: city.trim(),
      district: district.trim(),
      detailed_address: detailed_address.trim(),
      is_default: Boolean(is_default)
    };

    const newAddress = await UserAddress.create(addressData);
    res.success(newAddress, '创建地址成功');
  } catch (error) {
    console.error('创建地址失败:', error);
    res.error('创建地址失败', 500, error.message);
  }
});

/**
 * 更新地址
 * PUT /api/addresses/:id
 */
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    const {
      recipient_name, phone_number, province, city, district,
      detailed_address, is_default = false
    } = req.body;

    // 验证必填字段
    if (!recipient_name || !phone_number || !province || !city || !district || !detailed_address) {
      return res.error('请填写完整的地址信息', 400);
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone_number)) {
      return res.error('请输入正确的手机号', 400);
    }

    const addressData = {
      recipient_name: recipient_name.trim(),
      phone_number: phone_number.trim(),
      province: province.trim(),
      city: city.trim(),
      district: district.trim(),
      detailed_address: detailed_address.trim(),
      is_default: Boolean(is_default)
    };

    const updatedAddress = await UserAddress.update(id, userId, addressData);
    res.success(updatedAddress, '更新地址成功');
  } catch (error) {
    console.error('更新地址失败:', error);
    if (error.message === '地址不存在或无权限访问') {
      return res.error(error.message, 404);
    }
    res.error('更新地址失败', 500, error.message);
  }
});

/**
 * 删除地址
 * DELETE /api/addresses/:id
 */
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;

    const success = await UserAddress.delete(id, userId);
    if (success) {
      res.success(null, '删除地址成功');
    } else {
      res.error('删除地址失败', 500);
    }
  } catch (error) {
    console.error('删除地址失败:', error);
    if (error.message === '地址不存在或无权限访问') {
      return res.error(error.message, 404);
    }
    res.error('删除地址失败', 500, error.message);
  }
});

/**
 * 设置默认地址
 * PUT /api/addresses/:id/default
 */
router.put('/:id/default', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;

    const updatedAddress = await UserAddress.setDefault(id, userId);
    res.success(updatedAddress, '设置默认地址成功');
  } catch (error) {
    console.error('设置默认地址失败:', error);
    if (error.message === '地址不存在或无权限访问') {
      return res.error(error.message, 404);
    }
    res.error('设置默认地址失败', 500, error.message);
  }
});

/**
 * 获取默认地址
 * GET /api/addresses/default/info
 */
router.get('/default/info', async (req, res) => {
  try {
    const userId = req.user.userId;
    const defaultAddress = await UserAddress.getDefaultAddress(userId);
    
    if (!defaultAddress) {
      return res.error('未设置默认地址', 404);
    }

    res.success(defaultAddress, '获取默认地址成功');
  } catch (error) {
    console.error('获取默认地址失败:', error);
    res.error('获取默认地址失败', 500, error.message);
  }
});

module.exports = router;
